<script setup lang="tsx">
import { ref, reactive } from 'vue'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  type TableColumnCtx,
  FormInstance
} from 'element-plus'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Table, TableColumn } from '@/components/Table'
import { BaseButton } from '@/components/Button'
import SelectTable from './SelectTable.vue'
import { isNumber, cloneDeep } from 'lodash-es'
import { createApi, searchProductApi, searchProductCateApi } from '@/api/document'
// import { uploadFile } from '@/api/utils/upload'

const emit = defineEmits(['close', 'get-list'])
const loading = ref(false)

const TableSchema = reactive<TableColumn[]>([
  {
    field: 'action',
    label: '操作',
    slots: {
      default: ({ $index }) => {
        return $index > 0 ? (
          <>
            <BaseButton type="primary" onClick={addRow}>
              新增
            </BaseButton>
            <BaseButton onClick={() => delRow($index)}>删除</BaseButton>
          </>
        ) : (
          <BaseButton type="primary" onClick={addRow}>
            新增
          </BaseButton>
        )
      }
    }
  },
  {
    field: 'index',
    label: '序号',
    type: 'index'
  },
  {
    field: 'goods_name',
    label: '产品名称',
    slots: {
      default: ({ row, $index }) => {
        return (
          <div onClick={() => showSelectTableEl($index)} class="w-full h-full cursor-pointer">
            {row.goods_name ? row.goods_name : '点击选择进货产品'}
          </div>
        )
      }
    }
  },
  {
    field: 'spec_name',
    label: '规格'
  },
  {
    field: 'imgList',
    label: '图片',
    width: '100px'
  },
  {
    field: 'quantity',
    label: '数量',
    width: '200px',
    slots: {
      default: ({ row }) => {
        return <ElInputNumber v-model={row.quantity} min={1} step-strictly />
      }
    }
  },
  {
    field: 'purchasing_price',
    label: '进货单价（元）'
  },
  {
    field: 'purchasing_total_price',
    label: '进货总价（元）',
    formatter: (row) => {
      return (Number(row.purchasing_price) * Number(row.quantity)).toFixed(2)
    }
  }
])

interface Row {
  goods_id: number | null
  goods_rule_id: number | null
  spec_name: string
  goods_name: string
  img: string
  quantity: number
  purchasing_price: number | null
  purchasing_total_price: number | null
}
const dataList = ref<Row[]>([
  {
    goods_id: null,
    goods_rule_id: null,
    spec_name: '',
    goods_name: '',
    img: '',
    quantity: 1,
    purchasing_price: null,
    purchasing_total_price: null
  }
])
const currentRowIndex = ref<number>()

// 表格合并
interface SpanMethodProps {
  row: Row
  column: TableColumnCtx<Row>
  rowIndex: number
  columnIndex: number
}
const handleSpan = ({ row, columnIndex }: SpanMethodProps): any[] => {
  if (row.spec_name === '' && row.goods_name === '') {
    if (columnIndex === 2) return [1, 3]
    if (columnIndex === 3 || columnIndex === 4) return [0, 0]
  }
  return [1, 1]
}
// 合计
const summaryField = ['quantity', 'purchasing_total_price'] // 需要合计的字段
const getSummaries = (params) => {
  const { columns, data } = params
  const sums: string[] = ['合计：']
  columns.forEach((column, index) => {
    if (index === 0 || !summaryField.includes(column.property)) return
    const values = data.map((item) => {
      return column.property === 'purchasing_total_price'
        ? Number(item.purchasing_price) * Number(item.quantity)
        : Number(item[column.property])
    })
    if (!values.every((value) => Number.isNaN(value))) {
      const sum = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      sums[index] = sum.toFixed(2)
    }
  })
  return sums
}
// 点击选择商品
const showSelectTable = ref(false)

const showSelectTableEl = (index: number) => {
  currentRowIndex.value = index
  showSelectTable.value = true
}

const setTableData = (val) => {
  if (isNumber(currentRowIndex.value)) {
    const index = currentRowIndex.value
    const list = cloneDeep(dataList.value)
    const params = val.map((item) => {
      return {
        ...item,
        quantity: 1
      }
    })
    list.splice(index, 1, ...params)
    dataList.value = list.reduce((prev, cur) => {
      if (prev.length === 0) {
        prev.push(cur)
      } else {
        const cur_id = `${cur.goods_id}_${cur.goods_rule_id}`
        const index = prev.findIndex((item) => `${item.goods_id}_${item.goods_rule_id}` === cur_id)
        index >= 0 ? prev[index].quantity++ : prev.push(cur)
      }
      return prev
    }, [] as Row[])
  }
}

const addRow = () => {
  dataList.value.push({
    goods_id: null,
    goods_rule_id: null,
    spec_name: '',
    goods_name: '',
    img: '',
    quantity: 1,
    purchasing_price: null,
    purchasing_total_price: null
  })
}

const delRow = (index) => {
  dataList.value.splice(index, 1)
}
const formRef = ref<FormInstance>()
const formData = ref({
  remark: ''
})

const save = async () => {
  if (!dataList.value.every((item) => item.goods_id && item.goods_rule_id)) {
    ElMessage.error('请选择商品！')
    return false
  }
  try {
    const valid = await formRef.value?.validate().catch((err) => console.log(err))
    if (valid) {
      const params = {
        rules: dataList.value.map(({ goods_rule_id, quantity }) => {
          return {
            goods_rule_id,
            quantity
          }
        }),
        ...formData.value
      }
      // @ts-ignore
      const res = await createApi(params)
      if (res) {
        ElMessage.success(res.msg)
        emit('close')
        emit('get-list')
      }
    }
  } catch (err) {
    console.log(err)
  }
}
</script>

<template>
  <ContentDetailWrap title="新增采购单">
    <Table
      :columns="TableSchema"
      :data="dataList"
      :image-preview="['imgList']"
      height="500"
      :show-summary="true"
      :summary-method="getSummaries"
      :span-method="handleSpan"
      :show-overflow-tooltip="false"
    />
    <SelectTable
      v-model="showSelectTable"
      title="选择商品"
      :fetchData="searchProductApi"
      :fetchCateData="searchProductCateApi"
      @change="setTableData"
    />
    <el-form ref="formRef" :model="formData" label-width="auto" class="mt-[20px]">
      <el-form-item
        label="单据备注: "
        class="w-[300px]"
        prop="on_remark"
        :rules="[{ max: 100, message: '最多输入100字符', trigger: 'blur' }]"
      >
        <el-input
          v-model="formData.remark"
          type="textarea"
          autosize
          placeholder="请最多输入100字符"
          maxlength="100"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton type="primary" :loading="loading" @click="save">提交</BaseButton>
        <BaseButton @click="emit('close')">取消</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
